3 * Cache of various elements in a single cache entry.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @license GPL-2.0-or-later
22 * @author Jeroen De Dauw < jeroendedauw@gmail.com >
25 use MediaWiki\MediaWikiServices
;
28 * Helper class for caching various elements in a single cache entry.
30 * To get a cached value or compute it, use getCachedValue like this:
31 * $this->getCachedValue( $callback );
33 * To add HTML that should be cached, use addCachedHTML like this:
34 * $this->addCachedHTML( $callback );
36 * The callback function is only called when needed, so do all your expensive
37 * computations here. This function should returns the HTML to be cached.
38 * It should not add anything to the PageOutput object!
40 * Before the first addCachedHTML call, you should call $this->startCache();
41 * After adding the last HTML that should be cached, call $this->saveCache();
45 class CacheHelper
implements ICacheHelper
{
47 * The time to live for the cache, in seconds or a unix timestamp indicating the point of expiry.
52 protected $cacheExpiry = 3600;
55 * List of HTML chunks to be cached (if !hasCached) or that where cached (of hasCached).
56 * If not cached already, then the newly computed chunks are added here,
57 * if it as cached already, chunks are removed from this list as they are needed.
62 protected $cachedChunks;
65 * Indicates if the to be cached content was already cached.
66 * Null if this information is not available yet.
71 protected $hasCached = null;
74 * If the cache is enabled or not.
79 protected $cacheEnabled = true;
82 * Function that gets called when initialization is done.
87 protected $onInitHandler = false;
90 * Elements to build a cache key with.
95 protected $cacheKey = [];
98 * Sets if the cache should be enabled or not.
101 * @param bool $cacheEnabled
103 public function setCacheEnabled( $cacheEnabled ) {
104 $this->cacheEnabled
= $cacheEnabled;
108 * Initializes the caching.
109 * Should be called before the first time anything is added via addCachedHTML.
113 * @param int|null $cacheExpiry Sets the cache expiry, either ttl in seconds or unix timestamp.
114 * @param bool|null $cacheEnabled Sets if the cache should be enabled or not.
116 public function startCache( $cacheExpiry = null, $cacheEnabled = null ) {
117 if ( is_null( $this->hasCached
) ) {
118 if ( !is_null( $cacheExpiry ) ) {
119 $this->cacheExpiry
= $cacheExpiry;
122 if ( !is_null( $cacheEnabled ) ) {
123 $this->setCacheEnabled( $cacheEnabled );
126 $this->initCaching();
131 * Returns a message that notifies the user he/she is looking at
132 * a cached version of the page, including a refresh link.
136 * @param IContextSource $context
137 * @param bool $includePurgeLink
141 public function getCachedNotice( IContextSource
$context, $includePurgeLink = true ) {
142 if ( $this->cacheExpiry
< 86400 * 3650 ) {
143 $message = $context->msg(
144 'cachedspecial-viewing-cached-ttl',
145 $context->getLanguage()->formatDuration( $this->cacheExpiry
)
148 $message = $context->msg(
149 'cachedspecial-viewing-cached-ts'
153 if ( $includePurgeLink ) {
154 $refreshArgs = $context->getRequest()->getQueryValues();
155 unset( $refreshArgs['title'] );
156 $refreshArgs['action'] = 'purge';
158 $subPage = $context->getTitle()->getFullText();
159 $subPage = explode( '/', $subPage, 2 );
160 $subPage = count( $subPage ) > 1 ?
$subPage[1] : false;
162 $message .= ' ' . MediaWikiServices
::getInstance()->getLinkRenderer()->makeLink(
163 $context->getTitle( $subPage ),
164 $context->msg( 'cachedspecial-refresh-now' )->text(),
174 * Initializes the caching if not already done so.
175 * Should be called before any of the caching functionality is used.
179 protected function initCaching() {
180 if ( $this->cacheEnabled
&& is_null( $this->hasCached
) ) {
181 $cachedChunks = wfGetCache( CACHE_ANYTHING
)->get( $this->getCacheKeyString() );
183 $this->hasCached
= is_array( $cachedChunks );
184 $this->cachedChunks
= $this->hasCached ?
$cachedChunks : [];
186 if ( $this->onInitHandler
!== false ) {
187 call_user_func( $this->onInitHandler
, $this->hasCached
);
193 * Get a cached value if available or compute it if not and then cache it if possible.
194 * The provided $computeFunction is only called when the computation needs to happen
195 * and should return a result value. $args are arguments that will be passed to the
196 * compute function when called.
200 * @param callable $computeFunction
201 * @param array|mixed $args
202 * @param string|null $key
206 public function getCachedValue( $computeFunction, $args = [], $key = null ) {
207 $this->initCaching();
209 if ( $this->cacheEnabled
&& $this->hasCached
) {
212 if ( is_null( $key ) ) {
213 reset( $this->cachedChunks
);
214 $itemKey = key( $this->cachedChunks
);
216 if ( !is_int( $itemKey ) ) {
217 wfWarn( "Attempted to get item with non-numeric key while " .
218 "the next item in the queue has a key ($itemKey) in " . __METHOD__
);
219 } elseif ( is_null( $itemKey ) ) {
220 wfWarn( "Attempted to get an item while the queue is empty in " . __METHOD__
);
222 $value = array_shift( $this->cachedChunks
);
225 if ( array_key_exists( $key, $this->cachedChunks
) ) {
226 $value = $this->cachedChunks
[$key];
227 unset( $this->cachedChunks
[$key] );
229 wfWarn( "There is no item with key '$key' in this->cachedChunks in " . __METHOD__
);
233 if ( !is_array( $args ) ) {
237 $value = $computeFunction( ...$args );
239 if ( $this->cacheEnabled
) {
240 if ( is_null( $key ) ) {
241 $this->cachedChunks
[] = $value;
243 $this->cachedChunks
[$key] = $value;
252 * Saves the HTML to the cache in case it got recomputed.
253 * Should be called after the last time anything is added via addCachedHTML.
257 public function saveCache() {
258 if ( $this->cacheEnabled
&& $this->hasCached
=== false && !empty( $this->cachedChunks
) ) {
259 wfGetCache( CACHE_ANYTHING
)->set(
260 $this->getCacheKeyString(),
268 * Sets the time to live for the cache, in seconds or a unix timestamp
269 * indicating the point of expiry...
273 * @param int $cacheExpiry
275 public function setExpiry( $cacheExpiry ) {
276 $this->cacheExpiry
= $cacheExpiry;
280 * Returns the cache key to use to cache this page's HTML output.
281 * Is constructed from the special page name and language code.
286 * @throws MWException
288 protected function getCacheKeyString() {
289 if ( $this->cacheKey
=== [] ) {
290 throw new MWException( 'No cache key set, so cannot obtain or save the CacheHelper values.' );
293 return wfMemcKey( ...array_values( $this->cacheKey
) );
297 * Sets the cache key that should be used.
301 * @param array $cacheKey
303 public function setCacheKey( array $cacheKey ) {
304 $this->cacheKey
= $cacheKey;
308 * Rebuild the content, even if it's already cached.
309 * This effectively has the same effect as purging the cache,
310 * since it will be overridden with the new value on the next request.
314 public function rebuildOnDemand() {
315 $this->hasCached
= false;
319 * Sets a function that gets called when initialization of the cache is done.
323 * @param callable $handlerFunction
325 public function setOnInitializedHandler( $handlerFunction ) {
326 $this->onInitHandler
= $handlerFunction;